/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { Component } from "react";
import { connect } from "dva";
import { Tabs } from "antd";
import { parse } from "qs";
import "./index.less";

const TabPane = Tabs.TabPane;
const defaultName = "tab";

@connect(({ global }) => ({
  tabActiveKeys: global.tabActiveKeys,
}))
class StandardTab extends Component {
  constructor(props) {
    super(props);
    const { panes = [], tabActiveKeys, name = defaultName } = props;
    let activeKey = panes[0].key || "0";
    const { hash } = window.location;
    // 根据hash跳转对应tab
    if (hash) {
      const hashKey = hash.substring(1);
      const currentPane = panes.filter((item, index) => {
        const currentKey = item.key || index;
        if (currentKey == hashKey) {
          return true;
        }
      })[0];
      if (currentPane) {
        activeKey = hashKey;
      }
    } else if (tabActiveKeys && tabActiveKeys[name]) {
      activeKey = tabActiveKeys[name];
    }
    this.state = {
      activeKey,
    };
    this.changeTabActiveKey(activeKey, false);
  }

  changeTabActiveKey = (activeKey, isSet = true) => {
    const { dispatch, name = defaultName } = this.props;
    dispatch({
      type: "global/changeTabActiveKey",
      payload: {
        [name]: activeKey,
      },
    });
    if (isSet) {
      this.setState({
        activeKey,
      });
    }
  };

  componentDidUpdate( prevProps ){
    const { activeKey } = this.props;
    const { activeKey: prevActiveKey } = prevProps
    if( prevActiveKey && activeKey != prevActiveKey ){
      this.changeTabActiveKey(activeKey)
    }
  }

  handleChange = activeKey => {
    this.changeTabActiveKey(activeKey);
    const { onChange } = this.props;
    if (onChange) {
      onChange(activeKey);
    }
  };

  render() {
    const { activeKey } = this.state;
    const { panes, onChange, onTabClick, ...restPorps } = this.props;
    return (
      <div className="standard-tab">
        <Tabs type="card" onChange={this.handleChange} {...restPorps} activeKey={`${activeKey}`}>
          {panes &&
            panes.map((item, index) => {
              const { key = `${index}`, component, tab } = item;
              return (
                <TabPane
                  tab={
                    <a
                      onClick={() => {
                        if (onTabClick) {
                          onTabClick(`${key}`);
                        }
                      }}
                      href={`#${key}`}
                    >
                      {tab}
                    </a>
                  }
                  key={key}
                >
                  {component}
                </TabPane>
              );
            })}
        </Tabs>
      </div>
    );
  }
}

export default StandardTab;
